package edu.jd.software.web.backend.service.impl;

import edu.jd.software.web.backend.dto.UmsMenuNode;
import edu.jd.software.web.backend.mbg.mapper.UmsMenuMapper;
import edu.jd.software.web.backend.mbg.model.UmsMenuExample;
import edu.jd.software.web.backend.mbg.model.UmsMenu;
import edu.jd.software.web.backend.mbg.model.UmsMenuExample;
import edu.jd.software.web.backend.service.UmsMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class UmsMenuServiceImpl implements UmsMenuService {
    private Logger LOGGER = LoggerFactory.getLogger(this.getClass().getName());
    @Autowired
    private UmsMenuMapper menuMapper;

    @Override
    public List<UmsMenuNode> treeListCommon() {
        List<UmsMenu> menuList = menuMapper.selectByExample(new UmsMenuExample());
        List<UmsMenuNode> result =new ArrayList<UmsMenuNode>();

        for (UmsMenu menu:menuList){
            if (menu.getParentId()==0){//根菜单
                //调用 covertMenuNodeCommon 获得所有子菜单
                UmsMenuNode node =covertMenuNodeCommon(menu,menuList);
                result.add(node);
            }
        }
        return result;
    }

    /**
     * 将UmsMenu转化为UmsMenuNode并设置children属性-函数方式
     */
    private UmsMenuNode covertMenuNodeCommon(UmsMenu menuParent, List<UmsMenu> menuList) {
        UmsMenuNode node = new UmsMenuNode();
        //复制父类属性到新node
        BeanUtils.copyProperties(menuParent, node);

        List<UmsMenuNode> children =new ArrayList<UmsMenuNode>(); //children 所有子菜单
        for (UmsMenu menu:menuList){
            if (menu.getParentId()==menuParent.getId()){
                UmsMenuNode node_child =covertMenuNodeCommon(menu,menuList);
                children.add(node_child);
            }
        }
        node.setChildren(children);
        return node;
    }

    @Override
    public List<UmsMenuNode> treeListStream() {
        List<UmsMenu> menuList = menuMapper.selectByExample(new UmsMenuExample());
        List<UmsMenuNode> result =null;  //结果result
        //todo menuList 结果中的菜单以树形结构显示;
        //利用filter过滤出parentId=0的menu,
        //然后用map对一级菜单进行covertMenuNode操作，取到所有子菜单；

        return result;

    }

    /**
     * 将UmsMenu转化为UmsMenuNode并设置children属性-stream方式
     */
    private UmsMenuNode covertMenuNodeStream(UmsMenu menu, List<UmsMenu> menuList) {
        UmsMenuNode node = new UmsMenuNode();
        //复制父类属性到新node
        BeanUtils.copyProperties(menu, node);

        List<UmsMenuNode> children =null; //node 所有子菜单

        //todo 递归遍历出node的子菜单;
        //利用filter过滤出parentId为menu的Id的菜单，
        //然后用map继续covertMenuNode进行递归，获得menu的所有子菜单。


        node.setChildren(children);
        return node;

    }
}
